webix.ready(function(){
   var plans = JSON.parse($("#plans").val());
   var projectS = JSON.parse($("#gourps").val());
   var machines = JSON.parse($("#machines").val());
   var terminalArr = JSON.parse($("#terminals").val());
   var terminalstr = [];
   for(var i in terminalArr){
	   terminalstr[terminalstr.length] = terminalArr[i].terminal_id;
   }
   var batch = [{"id":"0","value":"否"},{"id":"1","value":"是"}];
     var my_templaet={
        template: "<span style='font-size:20px; font-weight:bold; color:#3498DB'; >生产排配</span>&nbsp;/&nbsp;&nbsp;ScheduleSheet",
        height:45,
        borderless:true 
    };
	var my_toolbar = {
			view : "toolbar",
			elements : [ {
				view : "combo",
				id : "plan_id",
				label : "选择计划",
				width : 260,
				labelWidth : 80,
				options : plans.data
			},  {
				view : "datepicker",
				id : "date",
				timepicker : true,
				label : "计划日期",
				labelAlign : "right",
				name : "end",
				stringResult : true,
				format : "%Y-%m-%d",
				width : 240,
			}, {
				view : "combo",
				id : "batch",
				label : "是否批量排配",
				width : 220,
				labelWidth : 120,
				options : batch
			}, {
				view : "button",
				value : "查询",
				width : 100,
				click : "select"
			} ,{
				id:"save",
				view : "button",
				value : "保存",
				width : 100,
				click : "save",
				hidden:true
			} ,
			{
				id:"ppbutton",
				view : "button",
				value : "排配审核",
				width : 100,
				click : "selectTerminal",
				hidden:true
			},
			{	
				id:"nowAchieve",
				view : "button",
				value : "立即下发",
				width : 100,
				click : "nowDown"
			},
			{	
				id:"sel_version",
				view : "button",
				value : "查看历史版本",
				width : 120,
				click : "sel_version",
				hidden:true
			},{
				id:"plan_desc",
				view:"label"
			},  ]
		};
	
	 var sel_terminal_form = {
			    view:"form",
			    id:"sel_terminal_form",
			    borderless:true,
			    complexData:true,
			    elements: [
			      { 
			        margin:20,
			        cols:[
			            
 			          { 
 			        	  view:"multiselect",
 			        	    id:"terminal_ids", 
 			        	    width:850,
 			        	    labelWidth:300,
  			        	    label:"选择该计划所使用的终端(默认所有):",  
 			        	    options:terminalArr,
 			        	    
 			        	    labelAlign:'left', 
 			        	    inputAlign:"left"
				          },
				         
			        ]
			      }, 
			      { 
				        margin:20,
				        cols:[
				            
	 			          { 
	 			        	  view:"checkbox",
	 			        	    id:"is_replace", 
	 			        	    width:850,
	 			        	    labelWidth:300,
	  			        	    label:"是否启用替换刀具:", 
	 			        	    labelAlign:'left', 
	 			        	    inputAlign:"left"
					          },
					         
				        ]
				      }, 
			      {
			        margin:10,
			        cols:[
			          {},
			          {view:"button",id:"btn4",value:'审核',click:"achieve",inputWidth:70,width:70}
			        ]
			      }
			    ]
			  
	 } 
	  var sel_terminal_toolbar={
			    view:"toolbar",
			    id:"sel_terminal_toolbar",
			    elements:[     
			      {view:"label", label: "排配审核",width:85},
			      {},
			      { view:"icon", icon:"times-circle", css:"alter",click:"$$('project').hide();"}
			    ], 
			  }
	 //查看历史版本
	 
	  var add_version_toolbar={
			    view:"toolbar",
			    id:"add_version_toolbar",
			    elements:[     
			      {view:"label", label: "排配历史版本查看",width:85},
			      {},
			      { view:"icon", icon:"times-circle", css:"alter",click:"$$('versionBody').hide();"}
			    ], 
			  }
	  var add_version_toolbar2={
			    view:"toolbar",
			    id:"add_version_toolbar",
			    elements:[     
			      {view:"label", label: "排配历史版本查看",width:120},
			      {},
			      { view:"icon", icon:"backward", css:"alter",click:"$$('versionScheduleBody').hide();$$('versionBody').show();"},
			      { view:"icon", icon:"times-circle", css:"alter",click:"$$('versionScheduleBody').hide();"}

			    ], 
			  }
	 var version_table={
		        view:"datatable",
		        id:"myversion",     
		        columns:[
		                 { id:"version",header:"版本信息",fillspace:true},
		                 { id:"version_date",header:"版本创建时间",fillspace:true}, 
		                 {id : "",
								template : "<a href='#' onclick=\"show_out_schedule('#version#')\">查看</a>",
								css : "padding_less",
								width : 120
							}

		        ],
		        height:600     
		   
		      };
	 var my_version_table={
		        view:"datatable",
		        id:"mydatatable",     
		        columns:[
 		                 { id:"project_name",header:"项目名称",width:100},
		                 { id:"project_id",header:"项目 id",hidden:true,fillspace:true},
		                 { id:"process_name",header:"工序",width:100},
		                 { id:"process_id",header:"工序id",hidden:true,fillspace:true},
		                 { id:"machine_ids",header:"参与机台",editor:"multiselect",optionslist:true,options:machines,inputWidth:300},
		                 { id:"classes_id",header:"班别",hidden:true,fillspace:true},
		                 { id:"classes_name",header:"班别",width:70},
		                 { id:"yield",header:"产量",width:70,editor:"text",template : function(obj, type) {
		    					if (obj.yield == 0) {
		    						return "0";
		    					}else{
		    						return obj.yield;
		    					}
		    				 }},
		                 { id:"gourp_ids",header:"安排班组",editor:"multiselect",optionslist:true,options:projectS,inputWidth:300},
		                 { id:"cust_cutter_spesc_id",header:"客户编码",hidden:true,fillspace:true},
		                 { id:"material_id",header:"物料编号",fillspace:true,hidden:true},
		                 { id:"customer_specs_no",header:"物料编码",fillspace:true},
 		                 { id:"long_specs_cust",header:"规格",fillspace:true},
		                 { id:"use_date",header:"安排日期",hidden:true,fillspace:true},
		                 { id:"schedule_status",header:"排配状态",hidden:true,fillspace:true},
		                 { id:"use_num",header:"数量",width:70} 
		        ],
		        height:600,      
		        editable:true,
				resizeColumn:true,
				tooltip:true,
		        spans:true,
		        select:"cell",
		        on:{
		            "onresize":webix.once(function(){ 
		                this.adjustRowHeight("machine_ids", true);
		                this.adjustRowHeight("gourp_ids", true); 
		            })
		            
		      
		        }
		      };
	    var versionBody=new webix.ui({
	    	view:"window",
	        width:1200,
	        id:"versionBody",
	        position:"center",
 	        rows:[
	              my_version_table
	        ],//----rows结束----
	    	modal:true,
	    	move:true,
	    	head:webix.copy(add_version_toolbar),
	   	    body:webix.copy(version_table)
 	    });
	    
	    var versionScheduleBody=new webix.ui({
	    	view:"window",
	        width:1600,
	        id:"versionScheduleBody",
	        position:"center",
 	        rows:[
	              my_version_table
	        ],//----rows结束----
	    	modal:true,
	    	move:true,
	    	head:webix.copy(add_version_toolbar2),
	   	    body:webix.copy(my_version_table)
 	    });
	 // window模态框
	  var project=new webix.ui({
	    view:"window",
	    id:'project',
	    width:1200,
	    position:"center",
	    modal:true,
	    move:true,
	    head:webix.copy(sel_terminal_toolbar),
	    body:webix.copy(sel_terminal_form)
	  });
      var my_treetable={
        view:"datatable",
        id:"mytable",
        columns:[
             { id:"project_name",header:["项目名称",{ content:"textFilter", placeholder:"请输入项目名称进行查询",}],fillspace:true},
             { id:"project_id",header:"项目 id",hidden:true,fillspace:true},
             { id:"process_name",header:"工序",fillspace:true},
             { id:"process_id",header:"工序id",hidden:true,fillspace:true},
             { id:"machine_ids",header:"参与机台",editor:"multiselect",optionslist:true,options:machines,inputWidth:300},
             { id:"classes_id",header:"班别",hidden:true,fillspace:true},
             { id:"classes_name",header:"班别",fillspace:true},
             { id:"yield",header:"产量",fillspace:true,editor:"text",template : function(obj, type) {
					if (obj.yield == 0) {
						return "0";
					}else{
						return obj.yield;
					}
				 }},
             { id:"gourp_ids",header:"安排班组",editor:"multiselect",optionslist:true,options:projectS,inputWidth:300},
             { id:"cust_cutter_spesc_id",header:"客户编码",hidden:true,fillspace:true},
             { id:"material_id",header:"物料编号",fillspace:true,hidden:true},
             { id:"customer_specs_no",header:"物料编码",fillspace:true},
             { id:"simple_specs_cust",header:"规格简称",fillspace:true},
             { id:"long_specs_cust",header:"规格",fillspace:true},
             { id:"use_date",header:"安排日期",hidden:true,fillspace:true},
             { id:"schedule_status",header:"排配状态",hidden:true,fillspace:true},
             { id:"version",header:"版本编号",hidden:true,fillspace:true},
             { id:"cutter_life",header:"寿命",hidden:true,fillspace:true},
            { id:"use_num",header:"数量（单击可修改）",fillspace:true,editor:"text"},
             { id:"now_num",header:"库存数量",width:70,fillspace:true}
          ],
        height:700,
        editable:true,
		resizeColumn:true,
		tooltip:true,
        spans:true,
        select:"cell",
        on:{
            "onresize":webix.once(function(){ 
                this.adjustRowHeight("machine_ids", true);
                this.adjustRowHeight("gourp_ids", true); 
            })
        }
     };
     var body=new webix.ui({
        container:"body",
        type:"line",
        id:"mylayout",
        rows:[
              my_templaet,
              my_toolbar,
              my_treetable,
             
          ],// ----rows结束----
// ----rows结束----
    });// ---webix.ui结束----
   	$$("nowAchieve").hide();
   	$$("mytable").attachEvent("onEditorChange", function(id, value){
   	  if(id.column=="yield"){
		  var tableValues={};
   		 $$("mytable").eachRow(function(row){
      		  var process_id = this.getItem(row)["process_id"];
      		  var classes_id = this.getItem(row)["classes_id"];
      		  var cutter_life = this.getItem(row)["cutter_life"];
      		  var now_num = this.getItem(row)["now_num"];
       		  if(this.getItem(id.row)["process_id"]==process_id&&this.getItem(id.row)["classes_id"]==classes_id){
      		  var use_num = parseInt(value)/parseInt(cutter_life);
      		  if(use_num>now_num){
      			use_num = now_num;
      		  }
      		  this.getItem(row)["use_num"]= parseInt(use_num);
      		  this.refresh(row);
      		  }
   		 })
   		  
    	  }
   
   	});;
});
//时间格式化
Date.prototype.Format = function(fmt) {
	var o = {
		"M+" : this.getMonth() + 1, //鏈堜唤   
		"d+" : this.getDate(), //鏃?   
		"h+" : this.getHours(), //灏忔椂   
		"m+" : this.getMinutes(), //鍒?   
		"s+" : this.getSeconds(), //绉?   
		"q+" : Math.floor((this.getMonth() + 3) / 3), //瀛ｅ害   
		"S" : this.getMilliseconds()
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	for ( var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1,
					(RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k])
							.substr(("" + o[k]).length)));
	return fmt;
}
function save(){
		  $$("save").disable();
		  $$("ppbutton").disable();
		  $$("mytable").editStop();
		  var plan_id = $$("plan_id").getValue();
		  var date = $$("date").getValue();
		  var batch = $$("batch").getValue();
		  var params = {};
		  var tableValues={};
		  var temp = new Array();
		  var i=0;
		  var flag = true;
		  var machineFlag = true;
		  var yieldFlag = true;
		  var dateFlag = true;
		  $$("mytable").eachRow( 
				  function (row){
				        tableValues[i]= $$("mytable").getItem(row);
				        temp[i]= $$("mytable").getItem(row);
				        if($$("date").getValue().substring(0,10)!=tableValues[i].use_date){
 				        	dateFlag= false;
				        	return false;	
				        }
				        if(i>0){
				        if(tableValues[i].classes_id==tableValues[i-1].classes_id && tableValues[i].process_id==tableValues[i-1].process_id){
				        	if(!tableValues[i].hasOwnProperty("gourp_ids")||tableValues[i].gourp_ids==""||tableValues[i].gourp_ids==null|| typeof tableValues[i].gourp_ids=="undefined"){
				        		tableValues[i].gourp_ids = tableValues[i-1].gourp_ids;
				        		temp[i].gourp_ids = tableValues[i-1].gourp_ids;
				        	} 
				        }
				        if(tableValues[i].classes_id==tableValues[i-1].classes_id && tableValues[i].process_id==tableValues[i-1].process_id){
				        	tableValues[i].yield = tableValues[i-1].yield;
				        		temp[i].yield = tableValues[i-1].yield;
				        }
				        
				        if(tableValues[i].process_id==tableValues[i-1].process_id){
			        		tableValues[i].machine_ids = tableValues[i-1].machine_ids;
			        		temp[i].machine_ids = tableValues[i-1].machine_ids;

			        }
				        }
				        i++;
				     
 				  });
		  	for (var j = 0; j < temp.length; j++) {
		  		if(temp[j].hasOwnProperty("gourp_ids")){
		  			if(temp[j].gourp_ids==""||temp[j].gourp_ids==null|| typeof temp[j].gourp_ids=="undefined"){
		  				flag = false;
		  			}
		  		}else{
					flag = false;
		  		}
				if(temp[j].hasOwnProperty("machine_ids")){
		  			if(temp[j].machine_ids==""||temp[j].machine_ids==null|| typeof temp[j].machine_ids=="undefined"){
		  				machineFlag = false;
		  			}
		  		}else{
		  			machineFlag = false;
		  		}
				
				if(temp[j].hasOwnProperty("yield")){
		  			if(temp[j].yield==""||temp[j].yield==null|| typeof temp[j].yield=="undefined"){
		  				yieldFlag = false;
		  			}
		  		}else{
		  			yieldFlag = false;
		  		}
			}
		  	// 获取单前时间
		  	var date2 = new Date().Format("yyyy-MM-dd")
		  	// 批量保存提示
		  	if(batch=="1"){
		  		if(!confirm(date2+"起 排配将会批量更新保存")){
		  			$$("ppbutton").enable();
					$$("save").enable();
			  		return ;
			  	}
		  	}else{
		  		batch = "0";
		  	}
		  	
		  	if(flag==true&&machineFlag==true){
		  		var cutterPlans = [];
		  		for (var prop in tableValues) {
					cutterPlans.push(tableValues[prop]);
				}
		  		params.plan_id = plan_id;
		  		params.date = date;
		  		params.batch = batch;
		        params.cutterPlans =JSON.stringify(cutterPlans);
			  if(params.cutterPlans=="{}"){
				  alert("未获取到数据");
				  $$("ppbutton").enable();
				  $$("save").enable();
				  return ;
			  }
			  if(dateFlag==true){
		       if(params.paramsArr!={}){
				  webix.ajax().sync().post("addNowCutterUsePlanHistory", params, function(text, xml, xhr){
					  var result=JSON.parse(text);
					  if(result.ret==1){
							alert("执行完毕");
							
					  }else{
						  alert(result.msg);
					  }
					select();
					$$("ppbutton").enable();
			  		$$("save").enable();
				});
			  }
			  }else{
		        	alert("当前表格未获取到"+$$("date").getValue().substring(0,10)+"的数据,请先点击查询再进行保存 ..")
		        	$$("ppbutton").enable();
			  		$$("save").enable();
			  }
			  
		  	}else{
		  		alert("未获取到组集合或机台集合,请确认数据无误");
		  		$$("ppbutton").enable();
		  		$$("save").enable();
		  	}
}

function selectTerminal(){
	  $$('project').show();
	  var terminalArr = JSON.parse($("#terminals").val());
	   var terminalstr = [];
	   for(var i in terminalArr){
		   terminalstr[terminalstr.length] = terminalArr[i].terminal_id;
	   }
	  $$('terminal_ids').setValue(terminalstr);
}
var versionData = [];
function sel_version(){ 
	  $$('versionBody').show();
	  var params = {};
		var plan_id = $$("plan_id").getValue();
		var date = $$("date").getValue();
		params.plan_id = plan_id;
		params.date = date;
	  webix.ajax().sync().post("getScheduleOutVersionList", params, function(text, xml, xhr){
			if(text!=""){ 
				var result=JSON.parse(text); 
				var data =result.data;
				versionData = data;
  				var resultArr =  [];
				var obj = {};
				for (var i = 0; i < data.length; i++) {
					obj[data[i].version]=data[i].version_date;
				}
	
				for(var i in obj){
					var verobj = {};
					verobj.version = i;
					verobj.version_date = obj[i]; 
					resultArr[resultArr.length] = verobj;
				}
  				$$('myversion').clearAll();
				 $$('myversion').define("data",resultArr); 
				 $$("myversion").refresh();

			}
	  })
}
function show_out_schedule(version){ 
	console.log(version);
	console.log(versionData);
	
	var newVersionData = [];
	for (var i = 0; i < versionData.length; i++) {
		if(version==versionData[i].version){ 
		newVersionData[newVersionData.length] =versionData[i];
		}
 	}
	  $$('versionBody').hide();
	  $$('versionScheduleBody').show();
	$$('mydatatable').clearAll();
	 $$('mydatatable').define("data",newVersionData); 
	 $$("mydatatable").refresh();
	 versionChuli(newVersionData); 
}


//对后台的数据进行分析，几个项目，几个工序
//对后台的数据进行分析，几个项目，几个工序

//对后台的数据进行分析，几个项目，几个工序
//对后台的数据进行分析，几个项目，几个工序
function versionChuli(data){
var d=data;
d.sort( function(a, b){   
 return (a["project_name"]) > (b["project_name"])? 1 : (a[ "project_name"]) == (b[ "project_name" ]) ? 0 : -1;   
}); 
var count=0;
var arryNew1=Array();
var arryNew2=Array();
var arryNew3=Array();
var arryNew4=Array();
var arryNew5=Array();
var temp="";
var b1=Array();
var b2=Array();
var b3=Array();
var b4=Array();
var b5=Array();
var b6=Array();
var ddd=0;
var ccc=0;
var eee=0;
var fff=0;
var ggg=0;
var hhh=0;
for(var i=0;i<d.length;i++){
 // 得到项目重复情况
   if(b1[i]!=-1){
     temp=d[i].project_name;
     for(var j=0;j<d.length;j++){
       if(temp==d[j].project_name){
         count++;
         b1[j] = -1;
       }
     }
     arryNew1.push(count);// 把这次循环的元素以及出现的次数保存到新的数组中
     count = 0;// 让count的值重新等于0
   }
}
//用于将数据排序得到调理好的数据
var sortArray1=new Array();
var sortArray2=new Array();
var sortArray3=new Array();
getSort(arryNew1,sortArray1,"process_name",d);
for(var k=0;k<arryNew1.length;k++){
ccc=ddd+arryNew1[k];
for(var j=ddd;j<ccc;j++){
 if(b2[j]!=-1){
   temp=d[j].process_name;
   for(var i=ddd;i<ccc;i++){
     // 判断
    if(temp==d[i].process_name){
       count++;
      b2[i] = -1;
     }
   } 
   arryNew2.push(count);// 把这次循环的元素以及出现的次数保存到新的数组中
   count = 0;// 让count的值重新等于0
 }
}
ddd=ccc;
}
getSort(arryNew2,sortArray2,"classes_name",d);
for(var k=0;k<arryNew2.length;k++){
eee=fff+arryNew2[k];
for(var j=fff;j<eee;j++){
 if(b3[j]!=-1){
   temp=d[j].classes_name;
   for(var i=fff;i<eee;i++){
     // 判断
    if(temp==d[i].classes_name){
     count++;
      b3[i] = -1;
     }
   } 
   arryNew3.push(count);// 把这次循环的元素以及出现的次数保存到新的数组中
   count = 0;// 让count的值重新等于0
 }
}
fff=eee;
}
$$('mydatatable').clearAll();
$$('mydatatable').define("data",d);
$$("mydatatable").refresh();
versionSpan(arryNew1,"project_name");
versionSpan(arryNew2, "process_name");
versionSpan(arryNew3, "classes_name");
versionSpan(arryNew3, "gourp_ids");
versionSpan(arryNew3, "yield");
versionSpan(arryNew2, "machine_ids");

$$("mydatatable").refresh();
}


function versionSpan(arryNew1,key){
  var e1;
  var f1=0;
  var f11=0;
  for(var i=0;i<arryNew1.length;i++){
        f11=f1+f11;
        e1=$$("mydatatable").getIdByIndex(f11);
         $$("mydatatable").addSpan([[e1, key, 1, arryNew1[i]],
        ]);
        f1=arryNew1[i];
　　}
}
function achieve(){
  $$("ppbutton").disable();
  $$("btn4").disable();
  $$("mytable").editStop();
  var params = {};
  var tableValues={};
  var temp = new Array();
  var i=0;
  var flag = true;
  var batch = $$("batch").getValue();
  $$("mytable").eachRow( 
  function (row){
        tableValues[i]= $$("mytable").getItem(row);
        temp[i]= $$("mytable").getItem(row);
        if(i>0){
        if(tableValues[i].classes_id==tableValues[i-1].classes_id && tableValues[i].process_id==tableValues[i-1].process_id){
        	if(!tableValues[i].hasOwnProperty("gourp_ids")||tableValues[i].gourp_ids==""||tableValues[i].gourp_ids==null|| typeof tableValues[i].gourp_ids=="undefined"){
        		tableValues[i].gourp_ids = tableValues[i-1].gourp_ids;
        		temp[i].gourp_ids = tableValues[i-1].gourp_ids;
        	}
        } 
        }
        i++;
  });
  	for (var j = 0; j < temp.length; j++) {
  		if(temp[j].hasOwnProperty("gourp_ids")){
  			
  			if(temp[j].gourp_ids==""||temp[j].gourp_ids==null|| typeof temp[j].gourp_ids=="undefined"){
  				flag = false;
  			}
  		}else{
			flag = false;
  		}
	}
  	// 获取单前时间
  	var date2 = new Date().Format("yyyy-MM-dd")
  	// 批量保存提示
  	if(batch=="1"){
  		if(!confirm(date2+"起 排配将会批量提交(仅操作定时下发计划)")){
  			$$("ppbutton").enable();
  			$$("save").enable();
	  		return ;
	  	}
  	}else{
  		batch = "0";
  	}
  	//flag =false;
  	if(flag==true){
  		var  terminalArray =  new Array ();
  		terminalArray = $$("terminal_ids").getValue();
      params.plan_id = $("#plan_id").val();
  	  params.date = $("#use_date").val();
  	  var terminalArrayStr = "";
  	  if(typeof(terminalArray)=="string"){
  		terminalArrayStr = terminalArray+",";
  	  }else{

  	  for (var i = 0; i < terminalArray.length; i++) {
  		terminalArrayStr+= terminalArray[i]+",";
	}
  	  }
   	  params.batch = batch;
   	  params.is_replace = $$("is_replace").getValue()
  	  params.terminal_ids = terminalArrayStr;
  	  console.log(params);
 		  webix.ajax().sync().post("completeSchedule", params, function(text, xml, xhr){
			  var result=JSON.parse(text);
 			  if(result.ret==1000){
				  $$("ppbutton").enable();
				  $$("save").enable();
				  $$("btn4").enable(); 
				  $$('project').hide();
				  alert("执行完毕");
				  select();
			  }else{
				  alert(result.msg);
				  $$("ppbutton").enable();
				  $$("save").enable();
				  $$("btn4").enable(); 
				  $$('project').hide();
				  select();
			  }
		  });
  	}else{
  		$$("ppbutton").enable();
  		alert("未获取到组集合,请重新添加");
  		
  	}
}
function nowDown(){
	  $$("nowAchieve").disable();
	  $$("mytable").editStop();
	  var params = {};
	  var tableValues={};
	  var temp = new Array();
	  var i=0;
	  var flag = true;
	  $$("mytable").eachRow( 
	  function (row){
	        tableValues[i]= $$("mytable").getItem(row);
	        temp[i]= $$("mytable").getItem(row);
	        if(i>0){
	        if(tableValues[i].classes_id==tableValues[i-1].classes_id && tableValues[i].process_id==tableValues[i-1].process_id){
	        	if(!tableValues[i].hasOwnProperty("gourp_ids")||tableValues[i].gourp_ids==""||tableValues[i].gourp_ids==null|| typeof tableValues[i].gourp_ids=="undefined"){
	        		temp[i].gourp_ids = tableValues[i-1].gourp_ids;
	        	}
	        } 
	        }
	        i++;
	  });
	  	for (var j = 0; j < temp.length; j++) {
	  		if(temp[j].hasOwnProperty("gourp_ids")){
	  			if(temp[j].gourp_ids==""||temp[j].gourp_ids==null|| typeof temp[j].gourp_ids=="undefined"){
	  				flag = false;
	  			}
	  		}else{
				flag = false;
	  		}
		}
	  	if(flag==true){
	      params.plan_id = $("#plan_id").val();
	  	  params.date = $("#use_date").val();
		  if(params.paramsArr!={}){
			  webix.ajax().sync().post("addPlanDetail", params, function(text, xml, xhr){
				  var result=JSON.parse(text);
				  if(result.ret==1){
						alert("执行完毕");
				  }else{
				  alert(result.msg);
				  }
				select();
				 
			});
		  }
	  	}else{
	  		alert("未获取到组集合,请重新添加");
	  		$$("ppbutton").enable();
	  	}
	}
function callback(data){
  // 第一次请求需要得到所有项目的选项以及已经安排的计划数据
  var text1=JSON.parse(data); 
// var data = new webix.DataCollection({data:text1.data});
// $$('mytable').data.sync(data);
 $$('mytable').clearAll();
		  $$('mytable').define("data",text1.data);
		  $$("mytable").refresh();
}
function select(){
	$$("nowAchieve").enable();
	$$("nowAchieve").hide();
 
	var params = {};
	var plan_id = $$("plan_id").getValue();
	var date = $$("date").getValue();
	params.plan_id = plan_id;
	params.date = date;
	webix.ajax().sync().post("getPlanDetailList", params, function(text, xml, xhr){
		if(text==""){
			alert("该计划"+date.substring(0,10)+"无排配")
			return false;
		}
		var result=JSON.parse(text);
		 
		  var plan=result.plan_data;
		  $("#plan_id").val(plan_id);
		  $("#use_date").val(date);
		  $("#is_auto").val(plan.is_auto);
		  var plan_str = "";
		  if(plan.is_auto==1){
			  plan_str = "该计划为定时下发，下发时间为 "+plan.issuedTime;
 		  }else if(plan.is_auto==0){
			  plan_str = "该计划为立即下发，当点击完成排配则立即下发";
			  $$("nowAchieve").hide();
		  } 
		 $$("plan_desc").define("label", plan_str);
		 $$('plan_desc').refresh();
 		 // var data = new webix.DataCollection({data:result.data});
		 // $$('mytable').data.sync(data);
		 $$('mytable').clearAll();
		  $$('mytable').define("data",result.data);
		 $$("mytable").refresh();
		 var scheduleFlag = true;
		 var arr = result.data;
			for (var i = 0; i < arr.length; i++) {
				$("#schedule_status").val(arr[i].schedule_status);
				if(arr[i].schedule_status==1){
			  		$$("save").show();
			  		$$("ppbutton").show();
				  }else if(arr[i].schedule_status==2){
				  		$$("save").show();
				  		$$("ppbutton").hide();
				  		 if(plan.is_auto==1){
						  		$$("ppbutton").hide();
						  		$$("nowAchieve").show();
						  }
				  }else{
					  plan_str = "该计划为立即下发,并且当前已经下发排配";
						 $$("plan_desc").define("label", plan_str);
						 $$('plan_desc').refresh();
						$$("save").show();
				  		$$("ppbutton").show();
				  		$$("nowAchieve").hide();
				  		$$("ppbutton").enable();
 				  		$$("save").enable();
				  } 
			  }
	  		$$("sel_version").show();

		  chuli(result.data);
    });
}	 

// 对后台的数据进行分析，几个项目，几个工序
// 对后台的数据进行分析，几个项目，几个工序
function chuli(data){
  var d=data;
  d.sort( function(a, b){   
    return (a["project_name"]) > (b["project_name"])? 1 : (a[ "project_name"]) == (b[ "project_name" ]) ? 0 : -1;   
}); 
  var count=0;
  var arryNew1=Array();
  var arryNew2=Array();
  var arryNew3=Array();
  var arryNew4=Array();
  var arryNew5=Array();
  var temp="";
  var b1=Array();
  var b2=Array();
  var b3=Array();
  var b4=Array();
  var b5=Array();
  var b6=Array();
  var ddd=0;
  var ccc=0;
  var eee=0;
  var fff=0;
  var ggg=0;
  var hhh=0;
  for(var i=0;i<d.length;i++){
    // 得到项目重复情况
      if(b1[i]!=-1){
        temp=d[i].project_name;
        for(var j=0;j<d.length;j++){
          if(temp==d[j].project_name){
            count++;
            b1[j] = -1;
          }
        }
        arryNew1.push(count);// 把这次循环的元素以及出现的次数保存到新的数组中
        count = 0;// 让count的值重新等于0
      }
  }
// 用于将数据排序得到调理好的数据
var sortArray1=new Array();
var sortArray2=new Array();
var sortArray3=new Array();
getSort(arryNew1,sortArray1,"process_name",d);
  for(var k=0;k<arryNew1.length;k++){
 ccc=ddd+arryNew1[k];
  for(var j=ddd;j<ccc;j++){
    if(b2[j]!=-1){
      temp=d[j].process_name;
      for(var i=ddd;i<ccc;i++){
        // 判断
       if(temp==d[i].process_name){
          count++;
         b2[i] = -1;
        }
      } 
      arryNew2.push(count);// 把这次循环的元素以及出现的次数保存到新的数组中
      count = 0;// 让count的值重新等于0
    }
  }
  ddd=ccc;
}
 getSort(arryNew2,sortArray2,"classes_name",d);
  for(var k=0;k<arryNew2.length;k++){
   eee=fff+arryNew2[k];
  for(var j=fff;j<eee;j++){
    if(b3[j]!=-1){
      temp=d[j].classes_name;
      for(var i=fff;i<eee;i++){
        // 判断
       if(temp==d[i].classes_name){
        count++;
         b3[i] = -1;
        }
      } 
      arryNew3.push(count);// 把这次循环的元素以及出现的次数保存到新的数组中
      count = 0;// 让count的值重新等于0
    }
  }
  fff=eee;
}
$$('mytable').clearAll();
  $$('mytable').define("data",d);
  $$("mytable").refresh();
　　span(arryNew1,"project_name");
　　span(arryNew2, "process_name");
　　span(arryNew3, "classes_name");
　　span(arryNew3, "gourp_ids");
   span(arryNew3, "yield");
   span(arryNew2, "machine_ids");

 $$("mytable").refresh();
}

function span(arryNew1,key){
  var e1;
  var f1=0;
  var f11=0;
  for(var i=0;i<arryNew1.length;i++){
        f11=f1+f11;
        e1=$$("mytable").getIdByIndex(f11);
        $$("mytable").addSpan([
           [e1, key, 1, arryNew1[i]],
        ]);
        f1=arryNew1[i];
　　}
}
function getSort(arryNew2,sortArray2,key,d){
var p3=0;
var p4=0;
  for(var i=0;i<arryNew2.length;i++){
          sortArray2[i]=new Array();
          p3=p3+p4;
          for(var j=p3;j<p3+arryNew2[i];j++){
            sortArray2[i][j]=d[j];
          }
          sortArray2[i].sort( function(a, b){   
            return (a[key]) > (b[key])? 1 : (a[key]) == (b[key]) ? 0 : -1;  
          });
          var l=0;
          for(var k=p3;k<p3+arryNew2[i];k++){
            d[k]=sortArray2[i][l++];
          } 
          p4=arryNew2[i];
  　　}
}
function funcation11(){
	alert(111);
}